package com.dwyinyuan.producer.file;

import com.dwyinyuan.enums.FileTypeEnums;
import com.dwyinyuan.model.FileDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.concurrent.BlockingQueue;

// http://www.biib.cn/du/index/16.html
public class BiibProducer implements Runnable {

    private String name;
    private BlockingQueue<FileDTO> blockingQueue;

    public BiibProducer(String name, BlockingQueue<FileDTO> blockingQueue) {
        this.name = name;
        this.blockingQueue = blockingQueue;
    }


    @Override
    public void run() {
        try {
            String baseUrl = "http://www.biib.cn";
            Document document = Jsoup.connect("http://www.biib.cn/du/index/24.html").get();
            // 选择具有特定class的div元素
            Element arclistDiv = document.select("div.arclist").first();
            // 在div元素中获取所有的ul列表
            Elements lis = arclistDiv.getElementsByClass("arc-item");
            for (Element li : lis) {
                //详情地址
                String href = baseUrl + li.select("a").get(0).attr("href");
                Document detail_doc = Jsoup.connect(href).get();
                String title = detail_doc.getElementsByClass("arc-title index-title").get(0).text();
                Elements articleBody = detail_doc.getElementsByClass("article-body");
                if(CollectionUtils.isEmpty(articleBody.select("a[href]"))){
                    continue;
                }
                String picUrl = baseUrl + articleBody.select("a[href]").get(0).attr("href");
                Elements source = detail_doc.select("source");
                if (source.isEmpty()) {
                    continue;
                }
                Element audio = source.get(0);
                String audioUrl = baseUrl + audio.attr("src");
                blockingQueue.put(new FileDTO(picUrl, title, FileTypeEnums.PIC.getCode()));
                blockingQueue.put(new FileDTO(audioUrl, title, FileTypeEnums.PIC.getCode()));
//                System.out.println("producer file name is " + title + " url is " + picUrl + " and " + audioUrl);
            }
            //消费者根据""退出while循环
            blockingQueue.put(new FileDTO(false));
            System.out.println("biib producer is over");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
